function Validation() {

}
Validation.prototype.isnull = function (value) {
    return value != undefined && value != "" && value.length > 0;
};
Validation.prototype.createDate = function(text,$dv){
    $("<div></div>")
        .addClass("msg")
        .text(text)
        .appendTo($dv.parent());
};
Validation.prototype.vali = function($dv,fun,title){
    $dv.focus(function () {
        $dv.css("border-bottom","1px solid #0084ff");
        $dv.siblings(".msg").remove();
    });
    $dv.blur(function () {
        $dv.css("border-bottom","1px solid #ebebeb");
        var inputVal = $dv.val();
        if (fun == "rePassword"){
            var password = $('#password').val();
            if(!Validation.prototype.valueEq(inputVal,password)){
                Validation.prototype.createDate(title,$dv);
            }
        }else{
            if(!Validation.prototype[fun](inputVal)){
                Validation.prototype.createDate(title,$dv);
            }else{
                if(fun == "username"){
                    $.post("/users/verify",{type:"username",value:inputVal},function (data) {
                        if(data.state == "no"){
                            Validation.prototype.createDate("用户名已经存在",$dv);
                        }
                    },"json")
                }else if(fun == "email"){
                    $.post("/users/verify",{type:"email",value:inputVal},function (data) {
                        if(data.state == "no"){
                            Validation.prototype.createDate("邮箱已经存在",$dv);
                        }
                    },"json")
                }else if(fun == "iphone"){
                    $.post("/users/verify",{type:"iphone",value:inputVal},function (data) {
                        if(data.state == "no"){
                            Validation.prototype.createDate("手机号已经存在",$dv);
                            $("#codeBtn").attr("disabled","disabled");
                        }else{
                            $("#codeBtn").removeAttr("disabled");
                        }
                    },"json")
                }
            }
        }

    });
};
Validation.prototype.valueEq = function (value1,value2) {
    return  value1 == value2;
};
Validation.prototype.username = function (name) {
    return /^[a-zA-Z0-9]{4,16}$/.test(name)
};

Validation.prototype.email = function (email) {
    return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(email);
};

Validation.prototype.iphone = function (iphone) {
    return  /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/.test(iphone);
};

Validation.prototype.password = function (password) {
    return /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/.test(password);
};
$(function () {
    // 检查手机验证码
    var $sendCodeBtn = $("#code~button");
    var time = $.cookie("sendCode");
    if( !isNaN(time) ){
        sendCode($sendCodeBtn,time);
    }
    // var username = $("#username").val();
    var $password = $("#password");
    var $repassword = $("#rePassword");
    var $email = $("#email");
    var $iphone = $("#IPhone");
    var $username = $("#username");

    var vd = new Validation();

    vd.vali($username, "username", '用户名4-16');
    vd.vali($password, "password", "需要包含字母数字");
    vd.vali($email, "email", "email格式错误");
    vd.vali($iphone, "iphone", '电话格式错误');
    vd.vali($repassword, "rePassword", '密码不一致');

    $(".register_item_b > button[type='submit']").click(function () {
        $(".register_item input").blur();
        if ($(".msg").length != 0) {
            //return false;
        }
        // TODO 验证手机验证码
        var $code = $("#code");
        if(!vd.isnull($code.val())){
            $code.css("border-bottom",'1px solid #f1403c');
            $code.focus(function () {
                $code.css("border-bottom","1px solid #0084ff");
            });
            $code.blur(function () {
                $code.css("border-bottom","1px solid #ebebeb");
            });
            return false;
        }
        var code = $code.val();
        var f = false;
        $.ajax({
            async : false,
            type: "POST",
            url : "/users/checkIphoneCode",
            data : {"code":code},
            success : function (data) {
                var state = data.state;
                if(state == "ok"){
                    f = true;
                }else if(data.state =="no"){
                    layer.msg('手机验证码输入有误', {
                        time: 2000, //20s后自动关闭
                    });
                    $iphone.css("border-bottom",'1px solid #f1403c');
                    $iphone.select();
                }else if(data.state == "timeout"){
                    layer.msg('验证码已经过期，请重新获得验证', {
                        time: 2000, //20s后自动关闭
                    });
                }else{
                    layer.msg('服务器开了一会小差', {
                        time: 2000, //20s后自动关闭
                    });
                }
            },
            dataType : "JSON"
        });
        if(f){
            return true;
        }else {
            $code.css("border-bottom",'1px solid #f1403c');
            return false;
        }
    });



    var handler = function (captchaObj) {
        captchaObj.onReady(function () {
            $("#wait").hide();
        }).onSuccess(function () {
            var result = captchaObj.getValidate();
            if (!result) {
                return alert('请完成验证');
            }else{
                sendCode($sendCodeBtn);
                // 验证成功
                var iphone = $("#IPhone").val();
                $.post("/users/sendIphoneCode",{"iphone":iphone},function (data) {
                    if(data.state == "ok"){
                        /*alert("短信发送成功");*/
                        layer.msg('短信发送成功', {
                            time: 2000, //20s后自动关闭
                        });
                    }else if(data.state == "no"){
                        layer.msg('请稍后再发送', {
                            time: 2000, //2s后自动关闭
                        });

                    }else if(data.state == "iphone number error"){
                        layer.msg('电话号码输入有误', {
                            time: 2000, //20s后自动关闭
                        });
                        $iphone.css("border-bottom",'1px solid #f1403c');
                        $iphone.select();
                    }else{
                        layer.msg('短信验证发送失败', {
                            time: 2000, //20s后自动关闭
                        });
                    }


                },"json");
            }
        });

        $sendCodeBtn.click(function () {
            captchaObj.verify();

        }.bind($sendCodeBtn))
};


    /*$sendCodeBtn.click(function () {

    };*/



    $.ajax({
        url: "/startCaptcha?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {

            // 调用 initGeetest 进行初始化
            // 参数1：配置参数
            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
            initGeetest({
                // 以下 4 个配置参数为必须，不能缺少
                gt: data.gt,
                challenge: data.challenge,
                offline: !data.success, // 表示用户后台检测极验服务器是否宕机
                new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
                timeout: '5000',
                product: "bind", // 产品形式，包括：float，popup
                width: "300px",
                https: true

            }, handler);
        }
    });



});
function sendCode($dv,t) {
    var time = t || 60;
    if(time == 60){
        $.cookie("sendCode", time,{path:"/users"});
    }
    window.timeId =setInterval(function () {
        if(time <= 0){
            $dv.removeAttr("disabled");
            $dv.html("发送验证码");
            clearInterval(window.timeId);
            $.cookie("sendCode",null);
        }else{
            $dv.prop("disabled","true");
            $dv.html(time+"s后发送");
            time --;
            $.cookie("sendCode",time);
        }
    },1000);
}
